/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：Users                                                    
*│　作    者：NetCoreCMS                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-12-25 10:52:46                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： NetCoreCMS.Services                                  
*│　类    名： UsersService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using NetCoreCMS.IRepository;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetCoreCMS.Services
{
    public class UsersService : IUsersService
    {
        private readonly IUsersRepository _repository;
        private readonly IUser_groupsRepository _user_groups;
        private readonly IUser_point_logService _user_point_log;
        private readonly IUser_amount_logService _user_amount_log;
        private readonly IUser_codeRepository _user_code;
        public UsersService(IUsersRepository repository, IUser_groupsRepository user_groups, IUser_point_logService user_point_log, IUser_amount_logService user_amount_log,IUser_codeRepository user_code)
        {
            _repository = repository;
            _user_groups = user_groups;
            _user_point_log = user_point_log;
            _user_amount_log = user_amount_log;
            _user_code = user_code;
        }

        public bool Exists(string username)
        {
            return _repository.Exists(username);
        }

        public bool Exists(int id)
        {
            return _repository.Get(id) != null ? true : false;
        }

        public bool Upgrade(int id)
        {
            if (!Exists(id))
            {
                return false;
            }
            Models.Users model = _repository.Get(id);
            Models.User_groups groupModel = _user_groups.GetUpgrade(model.group_id, model.exp);
            if (groupModel == null)
            {
                return false;
            }
            model.group_id = groupModel.id;
            int result = _repository.Update(model);
            if (result > 0)
            {
                //增加积分
                if (groupModel.point > 0)
                {
                    _user_point_log.Add(model.id, model.user_name, groupModel.point, "升级获得积分", true);
                }
                //增加金额
                if (groupModel.amount > 0)
                {
                    _user_amount_log.Add(model.id, model.user_name, groupModel.amount, "升级赠送金额");
                }
            }
            return true;
        }
        public List<Models.Users> GetList(int pageNumber, int rowsPerPage, string conditions, string orderby, object parameters = null)
        {
            return _repository.GetListPaged(pageNumber, rowsPerPage, conditions, orderby, parameters).ToList();
        }
        public int RecordCount(string conditions, object parameters = null)
        {
            return _repository.RecordCount(conditions, parameters);
        }

        public bool Delete(int id)
        {
            var user = GetModel(id);
            if (user.is_pass == 1)
                return false;
            var iuser = GetModel(user.iid);
            while (iuser != null)
            {
                UpdateField(iuser.id, "team_users-=1");
                iuser = GetModel(iuser.iid);
            }
            return _repository.DeleteAll(id);
        }

        public int UpdateField(int id, string strValue)
        {
            return _repository.UpdateField(id, strValue);
        }
        public List<Models.Users> GetList(string conditions)
        {
            return _repository.GetList(conditions).ToList();
        }

        public Users GetModel(int id)
        {
            return _repository.Get(id);
        }
        public Users GetModel(string user_name)
        {
            return _repository.Get("select * from ["+nameof(Users)+"] where user_name=@user_name and status<3", new { user_name = user_name });
        }
        public int Add(Users model)
        {
            var iuser = GetModel(model.iid);
            while (iuser != null)
            {
                UpdateField(iuser.id, "team_users+=1");
                iuser = GetModel(iuser.iid);
            }
            int id = (int)_repository.Insert(model);
            UpdateField(id, "user_id=" + id);
            return id;
        }

        public bool Update(Users model)
        {
            return _repository.Update(model) > 0;
        }
        public string GetSalt(string user_name)
        {
            //尝试用户名取得Salt
            var user = _repository.Get("select * from [" + nameof(Users) + "] where user_name=@user_name", new { user_name = user_name });
            if (user!=null)
            {
                if (!string.IsNullOrEmpty(user.salt))
                    return user.salt;
            }
            //尝试用手机号取得Salt
            user = _repository.Get("select * from [" + nameof(Users) + "] where mobile=@mobile", new { mobile = user_name });
            if (user != null)
            {
                if (!string.IsNullOrEmpty(user.salt))
                    return user.salt;
            }
            //尝试用邮箱取得Salt
            user = _repository.Get("select * from [" + nameof(Users) + "] where email=@email", new { email = user_name });
            if (user != null)
            {
                if (!string.IsNullOrEmpty(user.salt))
                    return user.salt;
            }
            return string.Empty;
        }
        public Users GetModel(string user_name, string password, int emaillogin, int mobilelogin, bool is_encrypt)
        {
            //检查一下是否需要加密
            if (is_encrypt)
            {
                //先取得该用户的随机密钥
                string salt = GetSalt(user_name);
                if (string.IsNullOrEmpty(salt))
                {
                    return null;
                }
                //把明文进行加密重新赋值
                password = AESEncryptHelper.Encode(password, salt);
            }
            return _repository.GetModel(user_name, password, emaillogin, mobilelogin);
        }

        public bool Exists(string reg_ip, int regctrl)
        {
            var model = _repository.Get("select * from [" + nameof(Users) + "] where reg_ip=@reg_ip and DATEDIFF(hh,reg_time,getdate())<@regctrl", new { reg_ip=reg_ip,regctrl=regctrl});
            return model != null ? true : false;
        }

        public bool ExistsEmail(string email)
        {
            var model = _repository.Get("select * from [" + nameof(Users) + "] where email=@email", new { email = email });
            return model != null ? true : false;
        }

        public bool ExistsMobile(string mobile)
        {
            var model = _repository.Get("select * from [" + nameof(Users) + "] where mobile=@mobile", new { mobile = mobile });
            return model != null ? true : false;
        }

        public List<User_code> get_user_invite_list(int top, string strwhere)
        {
            string _where = "where type='" + CMSEnums.CodeEnum.Register.ToString() + "'";
            if (!string.IsNullOrEmpty(strwhere))
            {
                _where += " and " + strwhere;
            }
            var list = _user_code.GetList(_where).OrderByDescending(a => a.add_time).OrderByDescending(a => a.id).ToList();
            if (top > 0)
                list = list.Take(top).ToList();
            return list;

        }
        /// <summary>
        /// 返回邀请码状态
        /// </summary>
        /// <param name="str_code">邀请码</param>
        /// <returns>bool</returns>
        public bool get_invite_status(string str_code)
        {
            Models.User_code model = _user_code.GetModel(str_code);
            if (model != null)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 返回一个随机用户名
        /// </summary>
        public string GetRandomName(int length)
        {
            string temp = Utils.Number(length, true);
            if (Exists(temp))
            {
                return GetRandomName(length);
            }
            return temp;
        }

        public List<Users> GetListPid(int id)
        {
            return _repository.GetList("where user_id>0 and pid=" + id).ToList();
        }

        public List<Users> GetListIid(int id)
        {
            return _repository.GetList("where user_id>0 and iid=" + id).ToList();
        }

        /// <summary>
        /// 左右区人
        /// </summary>
        /// <param name="indirectid"></param>
        /// <param name="leftright">1 left,2 right</param>
        /// <returns></returns>
        public Users GetUserByIndirectID(int iid, int leftright)
        {
            var lr = GetListIid(iid);
            if (lr.Count > 1)
            {
                if (leftright == 1)
                {
                    return lr[0];
                }
                else if (leftright == 2)
                {
                    return lr[1];
                }
            }
            if (lr.Count == 1)
            {
                if (leftright == 1)
                {
                    return lr[0];
                }
                else if (leftright == 2)
                {
                    return null;
                }
            }
            return null;
        }
    }
}